using UnityEngine;
using TMPro;

public class WallDetection : MonoBehaviour
{

    public GameObject playerClonePrefab;
    public TextMeshProUGUI debugCoverLR;

    private Transform target;

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag.Equals("Player"))
        {
            Debug.LogFormat("Enter - {0}, {1}", other.gameObject.name, other.gameObject.tag);

            target = other.gameObject.transform;
            playerClone.SetActive(true);

            mat = target.gameObject.GetComponent<Renderer>().material;
            normalColor = mat.color;

            debugCoverLR.color = Color.green;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag.Equals("Player"))
        {
            Debug.LogFormat("Exit - {0}, {1}", other.gameObject.name, other.gameObject.tag);
            mat.color = normalColor;

            target = null;
            playerClone.SetActive(false);

            debugCoverLR.color = Color.white;
        }
    }

    Material mat;
    Color normalColor;
    Transform wall;
    bool isForward = false;

    GameObject playerClone;
    private void Start()
    {
        playerClone = GameObject.Instantiate(playerClonePrefab);
        playerClone.SetActive(false);

        wall = transform;
    }

    private void Update()
    {
        if (null == target)
        {
            return;
        }

        Vector3 wallDir = wall.forward;
        Vector3 wallToTargetDir = (target.position - wall.position).normalized;

        //=============================================================================
        //Player在墙的前面还是后面？
        float dot = Vector3.Dot(wallDir, wallToTargetDir);
        if (dot < 0)
        {
            //The Target is behind Wall
            mat.color = Color.red;
            isForward = false;
        }
        else
        {
            mat.color = normalColor;
            isForward = true;
        }

        //=============================================================================
        //计算距离及角度

        //在wall的正前方是0度，正左方式90度，正右方也是90度；正后方是180度
        //float angle = Vector3.Angle(wallToTargetDir, wallDir);

        //在wall的正前方是0度，正左方是90度，正右方是 - 90度，正后方是180或 - 180度
        float angle = Vector3.SignedAngle(wallToTargetDir, wallDir, Vector3.up);
        angle += 90;

        float distance = Vector3.Distance(
            new Vector3(wall.position.x, 0, wall.position.z),
            new Vector3(target.position.x, 0, target.position.z));
        float a = distance * Mathf.Sin(angle * Mathf.Deg2Rad);
        float b = distance * Mathf.Cos(angle * Mathf.Deg2Rad);

        Debug.DrawLine(target.position, wall.position, Color.blue);
        //当Wall旋转后，该算法错误
        //Vector3 pos = wall.position + new Vector3(b, 0, 0);
        Vector3 pos = wall.position + wall.right * b;
        Debug.DrawLine(target.position, pos, Color.red);


        //=============================================================================
        //计算Player是使用左掩护还是右掩护动画
        Vector3 targetDir = target.forward;

        //float angle = Vector3.Angle(targetDir, wallDir);
        float signedAngle = Vector3.SignedAngle(targetDir, wallDir, Vector3.up);
        //in front of the wall
        //SingledAngle > 0 = LeftCover
        //             < 0 = RightCover
        //Behind the wall
        //SingledAngle > 0 = RightCover
        //             < 0 = LeftCover

        isLeft = true;
        if (isForward)
        {
            if (signedAngle <= 0)
            {
                isLeft = false;
            }
        }
        else
        {
            if (signedAngle > 0)
            {
                isLeft = false;
            }
        }
        debugCoverLR.text = string.Format("{0}", isLeft ? "LEFT" : "RIGHT");

        //=============================================================================
        //放置示意Player
        if (isForward)
        {
            pos = pos + wall.forward * (wallThickness / 2f + playerRadius);
        }
        else
        {
            pos = pos + wall.forward * -1 * (wallThickness / 2f + playerRadius);
        }
        playerClone.transform.position = pos;

        if (isForward)
        {
            playerClone.transform.rotation = wall.transform.rotation;
        }
        else
        {
            playerClone.transform.rotation = Quaternion.LookRotation(-wall.transform.forward);
        }
    }
    bool isLeft = false;
    float wallThickness = 0.4f;
    float playerRadius = 0.5f;

}
